<template>
  <template v-for="item in rootItems" :key="item.id">
    <el-sub-menu v-if="hasChildren(item.id)" :index="item.id.toString()">
      <template #title>
        <el-icon><Document /></el-icon>
        <span>{{ item.label }}</span>
        <el-icon class="add-icon" @click.stop="handleAdd(item)">
          <CirclePlusFilled />
        </el-icon>
      </template>
      <template v-for="child in getChildren(item.id)" :key="child.id">
        <el-sub-menu v-if="hasChildren(child.id)" :index="child.id.toString()">
          <template #title>
            <el-icon><Document /></el-icon>
            <span>{{ child.label }}</span>
            <el-icon class="add-icon" @click.stop="handleAdd(child)">
              <CirclePlusFilled />
            </el-icon>
          </template>
          <el-menu-item
            v-for="grandChild in getChildren(child.id)"
            :key="grandChild.id"
            :index="grandChild.id.toString()"
          >
            <el-icon><Document /></el-icon>
            <span>{{ grandChild.label }}</span>
          </el-menu-item>
        </el-sub-menu>
        <el-menu-item v-else :index="child.id.toString()">
          <el-icon><Document /></el-icon>
          <span>{{ child.label }}</span>
          <el-icon class="add-icon" @click.stop="handleAdd(child)">
            <CirclePlusFilled />
          </el-icon>
        </el-menu-item>
      </template>
    </el-sub-menu>
    <el-menu-item v-else :index="item.id.toString()">
      <el-icon><Document /></el-icon>
      <span>{{ item.label }}</span>
      <el-icon class="add-icon" @click.stop="handleAdd(item)">
        <CirclePlusFilled />
      </el-icon>
    </el-menu-item>
  </template>
</template>

<script lang="ts">
import { defineComponent, PropType, computed } from "vue";
import type { HelpDoc } from "@/api/help";
import { Document } from "@element-plus/icons-vue";

export default defineComponent({
  name: "RecursiveMenu",
  components: {
    Document
  },
  props: {
    items: {
      type: Array as PropType<HelpDoc[]>,
      required: true
    },
    handleAdd: {
      type: Function,
      required: false
    }
  },
  setup(props) {
    const rootItems = computed(() => {
      return props.items.filter(item => item.parentId === 0);
    });
    const getChildren = (parentId: number) => {
      return props.items.filter(item => item.parentId === parentId);
    };
    const hasChildren = (parentId: number) => {
      return props.items.some(item => item.parentId === parentId);
    };
    return {
      rootItems,
      getChildren,
      hasChildren
    };
  }
});
</script>
<style scoped>
.el-sub-menu :deep(.add-icon),
.el-menu-item :deep(.add-icon) {
  margin-left: 10px;
}
</style>
